<template>
    <el-container
        class="h-screen overflow-hidden font-sans bg-gray-50 text-gray-800"
        style="height: calc(100vh - 84px)"
    >
        <!-- 顶部导航 -->
        <el-header
            class="bg-white shadow-sm border-b border-gray-200 p-3 flex items-center justify-between z-10"
        >
            <div class="flex items-center gap-3">
                <el-icon
                    @click="handleBack"
                    style="cursor: pointer"
                    class="ml-5"
                    ><ArrowLeftBold
                /></el-icon>
                <h1 class="text-lg font-semibold">
                    商业综合体建设项目 - 分部分项报价详情
                </h1>
            </div>

            <div class="flex items-center gap-3 mr-5">
                <el-button
                    type="default"
                    icon="Printer"
                    class="flex items-center gap-1.5 text-sm"
                    @click="handlePrint"
                >
                    打印
                </el-button>
                <el-button
                    type="default"
                    icon="Download"
                    class="flex items-center gap-1.5 text-sm"
                    @click="handleExport"
                >
                    导出
                </el-button>
                <el-button
                    type="primary"
                    icon="SuccessFilled"
                    class="flex items-center gap-1.5 text-sm"
                    @click="handleSave"
                >
                    保存
                </el-button>
            </div>
        </el-header>

        <!-- 主内容区 -->
        <el-container class="flex-1 overflow-hidden">
            <!-- 左侧分部分项导航（树结构） -->
            <el-aside
                width="220px"
                class="bg-white border-r border-gray-200 overflow-y-auto"
            >
                <div class="p-4 border-b border-gray-200">
                    <h2 class="font-medium">分部分项导航</h2>
                    <p class="text-xs text-gray-500 mt-1">点击项目查看详情</p>
                </div>
                <div class="p-2">
                    <el-tree
                        :data="treeData"
                        :props="treeProps"
                        :default-expanded-keys="[
                            'project-1',
                            'unit-1',
                            'section-1',
                        ]"
                        :highlight-current="true"
                        @current-change="handleTreeChange"
                        class="tree-container"
                    >
                        <!-- 自定义树节点样式（高亮当前选中项） -->
                        <template #default="{ data, node }">
                            <div
                                class="flex items-center py-1 px-2 rounded-md transition-colors"
                                :class="{
                                    'bg-primary/5 text-primary': node.isCurrent,
                                    'hover:bg-gray-50': !node.isCurrent,
                                }"
                            >
                                <span class="ml-1">{{ data.label }}</span>
                            </div>
                        </template>
                    </el-tree>
                </div>
            </el-aside>

            <!-- 右侧分部分项详情 -->
            <el-main class="overflow-y-auto bg-white p-6">
                <!-- 分部分项概览（卡片布局） -->
                <el-card class="mb-6" shadow="hover">
                    <div class="mb-4">
                        <h2 class="text-lg font-semibold">
                            混凝土结构工程 - 报价概览
                        </h2>
                    </div>

                    <!-- 统计卡片 -->
                    <el-row :gutter="20" class="mb-6">
                        <el-col :xs="12" :sm="8" :md="6">
                            <el-card class="h-full" shadow="hover">
                                <div class="text-sm text-gray-500 mb-1">
                                    分项工程数量
                                </div>
                                <div class="text-2xl font-bold">28 项</div>
                            </el-card>
                        </el-col>
                        <el-col :xs="12" :sm="8" :md="6">
                            <el-card class="h-full" shadow="hover">
                                <div class="text-sm text-gray-500 mb-1">
                                    总工作量
                                </div>
                                <div class="text-2xl font-bold">1,256.8 m³</div>
                            </el-card>
                        </el-col>
                        <el-col :xs="24" :sm="8" :md="12">
                            <el-card class="h-full" shadow="hover">
                                <div class="text-sm text-gray-500 mb-1">
                                    分项总造价
                                </div>
                                <div class="text-2xl font-bold text-danger">
                                    ¥ 1,085,680.00
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>

                    <!-- 造价占比图表 -->
                    <el-card shadow="hover">
                        <div class="text-sm font-medium mb-3">
                            各子项造价占比
                        </div>
                        <div class="h-48">
                            <canvas ref="costChartRef"></canvas>
                        </div>
                    </el-card>
                </el-card>

                <!-- 分部分项详细列表（带分页） -->
                <el-card shadow="hover">
                    <div
                        class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4 gap-3"
                    >
                        <h2 class="text-lg font-semibold">
                            分部分项工程量清单与计价表
                        </h2>
                        <div class="flex items-center gap-3 w-full sm:w-auto">
                            <!-- 搜索框 -->
                            <el-input
                                v-model="searchKeyword"
                                placeholder="搜索项目..."
                                size="small"
                                class="w-full sm:w-48"
                                prefix-icon="Search"
                            ></el-input>
                            <!-- 筛选下拉 -->
                            <el-select
                                v-model="selectedCategory"
                                placeholder="全部子项"
                                size="small"
                                @change="handleCategoryChange"
                            >
                                <el-option
                                    label="全部子项"
                                    value=""
                                ></el-option>
                                <el-option
                                    label="基础工程"
                                    value="基础工程"
                                ></el-option>
                                <el-option
                                    label="柱、梁工程"
                                    value="柱、梁工程"
                                ></el-option>
                                <el-option
                                    label="板、墙工程"
                                    value="板、墙工程"
                                ></el-option>
                            </el-select>
                        </div>
                    </div>

                    <!-- 表格 -->
                    <el-table
                        :data="filteredTableData"
                        border
                        size="small"
                        class="mb-4"
                        :row-class-name="tableRowClassName"
                    >
                        <el-table-column label="序号" width="60" align="center">
                            <template #default="scope">
                                {{
                                    scope.$index +
                                    1 +
                                    (currentPage - 1) * pageSize
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="编码"
                            width="100"
                            align="center"
                            prop="code"
                        />
                        <el-table-column
                            label="项目名称"
                            prop="name"
                            class-name="font-medium"
                        />
                        <el-table-column
                            label="项目特征描述"
                            prop="description"
                            width="300"
                        />
                        <el-table-column
                            label="计量单位"
                            width="80"
                            align="center"
                            prop="unit"
                        />
                        <el-table-column
                            label="工作量"
                            width="100"
                            align="right"
                            prop="quantity"
                        />
                        <el-table-column
                            label="综合单价(元)"
                            width="120"
                            align="right"
                            prop="unitPrice"
                        >
                            <template #default="scope">
                                {{ formatCurrency(scope.row.unitPrice) }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="合价(元)"
                            width="120"
                            align="right"
                            prop="totalPrice"
                            class-name="font-medium"
                        >
                            <template #default="scope">
                                {{ formatCurrency(scope.row.totalPrice) }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="备注"
                            width="80"
                            align="center"
                            prop="remark"
                        />
                    </el-table>

                    <!-- 分页 -->
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 20, 50]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="filteredTableData.length"
                        size="small"
                    ></el-pagination>
                </el-card>
            </el-main>
        </el-container>
    </el-container>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import Chart from "chart.js/auto"; // 引入Chart.js
import { useRouter } from "vue-router";
const router = useRouter();
// Element Plus 图标引入（按需引入，减少体积）
import { Printer, Download, Search } from "@element-plus/icons-vue";

// 1. 树结构数据（替代原手动DOM折叠，符合Vue响应式）
const treeData = ref([
    {
        id: "project-1",
        label: "商业综合体建设项目",
        children: [
            {
                id: "unit-1",
                label: "1. 主体结构工程",
                children: [
                    {
                        id: "section-1",
                        label: "1.1 混凝土结构工程",
                        children: [
                            { id: "item-1", label: "1.1.1 基础工程" },
                            { id: "item-2", label: "1.1.2 柱、梁工程" },
                            { id: "item-3", label: "1.1.3 板、墙工程" },
                        ],
                    },
                    { id: "section-2", label: "1.2 钢筋工程" },
                    { id: "section-3", label: "1.3 砌筑工程" },
                ],
            },
            { id: "unit-2", label: "2. 装饰装修工程" },
            { id: "unit-3", label: "3. 安装工程" },
        ],
    },
]);

const treeProps = ref({
    children: "children",
    label: "label",
});

// 2. 表格数据（静态数据转响应式，便于后续接口对接）
const tableData = ref([
    {
        code: "010501001",
        name: "现浇混凝土基础",
        description: "C30混凝土，垫层100mm厚C15混凝土，含模板及支撑",
        unit: "m³",
        quantity: 120.5,
        unitPrice: 865.2,
        totalPrice: 104256.6,
        remark: "-",
        category: "基础工程",
    },
    {
        code: "010501002",
        name: "设备基础",
        description: "C35混凝土，含预埋件，模板及支撑",
        unit: "m³",
        quantity: 38.2,
        unitPrice: 980.5,
        totalPrice: 37455.1,
        remark: "-",
        category: "基础工程",
    },
    {
        code: "010502001",
        name: "现浇混凝土柱",
        description: "C40混凝土，截面尺寸600×600mm，含模板及支撑",
        unit: "m³",
        quantity: 85.3,
        unitPrice: 980.5,
        totalPrice: 83636.65,
        remark: "-",
        category: "柱、梁工程",
    },
    {
        code: "010503001",
        name: "现浇混凝土梁",
        description: "C35混凝土，截面尺寸300×600mm，含模板及支撑",
        unit: "m³",
        quantity: 156.8,
        unitPrice: 925.3,
        totalPrice: 145087.04,
        remark: "-",
        category: "柱、梁工程",
    },
    {
        code: "010503002",
        name: "现浇混凝土过梁",
        description: "C30混凝土，含模板及支撑",
        unit: "m³",
        quantity: 28.6,
        unitPrice: 890.0,
        totalPrice: 25454.0,
        remark: "-",
        category: "柱、梁工程",
    },
    {
        code: "010504001",
        name: "现浇混凝土板",
        description: "C30混凝土，厚度120mm，含模板及支撑",
        unit: "m³",
        quantity: 256.3,
        unitPrice: 785.6,
        totalPrice: 201359.28,
        remark: "-",
        category: "板、墙工程",
    },
    {
        code: "010507001",
        name: "现浇混凝土墙",
        description: "C35混凝土，厚度200mm，含模板及支撑",
        unit: "m³",
        quantity: 328.5,
        unitPrice: 950.8,
        totalPrice: 312337.8,
        remark: "-",
        category: "板、墙工程",
    },
    {
        code: "010512001",
        name: "现浇混凝土楼梯",
        description: "C30混凝土，含模板及支撑",
        unit: "m³",
        quantity: 48.2,
        unitPrice: 1250.3,
        totalPrice: 60264.46,
        remark: "-",
        category: "板、墙工程",
    },
]);

// 3. 分页与筛选相关响应式数据
const currentPage = ref(1);
const pageSize = ref(8);
const searchKeyword = ref("");
const selectedCategory = ref("");
const costChartRef = ref(null);
let costChartInstance = null; // Chart实例引用

// 筛选后的表格数据（计算属性：实时响应搜索和筛选）
const filteredTableData = ref([]);
const updateFilteredData = () => {
    let result = [...tableData.value];
    // 搜索筛选
    if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        result = result.filter(
            (item) =>
                item.name.toLowerCase().includes(keyword) ||
                item.code.includes(keyword) ||
                item.description.toLowerCase().includes(keyword)
        );
    }
    // 分类筛选
    if (selectedCategory.value) {
        result = result.filter(
            (item) => item.category === selectedCategory.value
        );
    }
    filteredTableData.value = result;
    // 筛选后重置页码
    currentPage.value = 1;
};

// 监听搜索关键词变化
searchKeyword.value && updateFilteredData();
searchKeyword.value = ""; // 初始化搜索框
updateFilteredData(); // 初始加载筛选数据

// 4. 图表初始化（在DOM渲染后执行，避免DOM不存在的bug）
onMounted(async () => {
    await nextTick(); // 等待DOM完全渲染
    initCostChart();
});

// 初始化造价占比图表
const initCostChart = () => {
    if (!costChartRef.value) return;

    // 销毁旧图表（避免重复初始化导致的内存泄漏）
    if (costChartInstance) {
        costChartInstance.destroy();
    }

    const ctx = costChartRef.value.getContext("2d");
    costChartInstance = new Chart(ctx, {
        type: "doughnut",
        data: {
            labels: ["基础工程", "柱、梁工程", "板、墙工程"],
            datasets: [
                {
                    data: [141711.7, 254177.69, 578791.54],
                    backgroundColor: ["#165DFF", "#36CFC9", "#FAAD14"],
                    borderWidth: 0,
                    hoverOffset: 4,
                },
            ],
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: "right",
                    labels: {
                        boxWidth: 12,
                        padding: 15,
                        font: { size: 11 },
                    },
                },
                tooltip: {
                    callbacks: {
                        label: (context) => {
                            const label = context.label || "";
                            const value = context.raw || 0;
                            const total = context.dataset.data.reduce(
                                (a, b) => a + b,
                                0
                            );
                            const percentage = Math.round(
                                (value / total) * 100
                            );
                            return `${label}: ¥${value.toLocaleString()} (${percentage}%)`;
                        },
                    },
                },
            },
            cutout: "70%",
        },
    });
};

// 5. 事件处理函数
// 树节点切换
const handleTreeChange = (data) => {
    ElMessage.info(`当前选中：${data.label}`);
    // 可扩展：根据选中的树节点加载对应的数据
};

// 分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1; // 重置页码
};

// 当前页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val;
    // 滚动到表格顶部（优化体验）
    document.querySelector(".el-table").scrollTop = 0;
};

// 分类筛选变化
const handleCategoryChange = () => {
    updateFilteredData();
};

// 表格行样式（hover效果优化）
const tableRowClassName = () => {
    return "hover:bg-gray-50 transition-colors";
};

// 按钮事件（可根据实际需求扩展）
const handleBack = () => {
    ElMessage.info("返回上一页");
    router.back();
    // 实际项目中可使用vue-router的back()
};

const handlePrint = () => {
    ElMessage.info("触发打印功能");
    // 实际项目中可集成print-js等打印库
};

const handleExport = () => {
    ElMessage.info("触发导出功能");
    // 实际项目中可使用xlsx库导出Excel
};
const handleSave = () => {
    ElMessage.success("保存成功");
    // 实际项目中可对接保存接口
};

// 6. 工具函数（格式化货币）
const formatCurrency = (value) => {
    if (isNaN(value)) return "¥ 0.00";
    return (
        "¥ " +
        value.toLocaleString("zh-CN", {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        })
    );
};

// 7. 组件卸载时销毁图表（避免内存泄漏）
onUnmounted(() => {
    if (costChartInstance) {
        costChartInstance.destroy();
    }
});
</script>

<style scoped>
/* 基础样式优化 */
.el-container,
.el-aside,
.el-main,
.el-header {
    padding: 0;
    margin: 0;
}

/* 树节点样式优化 */
.tree-container .el-tree-node {
    padding: 2px 0;
}

/* 卡片间距优化 */
.el-card + .el-card {
    margin-top: 20px;
}

/* 响应式适配：小屏幕下树收缩 */
@media (max-width: 768px) {
    .el-aside {
        width: 180px !important;
    }
    .el-main {
        padding: 4px !important;
    }
}

/* 表格表头样式优化 */
::v-deep .el-table__header th {
    background-color: #f5f7fa !important;
    font-weight: 500 !important;
}

/* 分页样式优化 */
::v-deep .el-pagination {
    text-align: right;
    margin-top: 16px;
}
</style>
